Objective: to create reports in PDF and HTML formats.
The rmarkdown package helps to create documents that combine code, rendered output, and text. These documents can help to:
Reproduce your analysis and reports
Communicate your results better
Do data science interactively
R Markdown can render documents in PDF, HTML, Word, slideshows among others. You can read the R Markdown: The Definitive Guide book.
You can install the rmarkdown package as follows:
# Install from CRAN
install.packages('rmarkdown')
# Or if you want to test the development version, install it from GitHub
install.packages('devtools')
devtools::install_github('rstudio/rmarkdown')In case that you want to render PDF documents you need to install LaTeX. For this purpose, TinyTeX is reccomended https://yihui.name/tinytex/.
The R scripts have the .R as file extension, while R Markdown documents have :Rmd. Once that the rmarkdown package is installed you will be able to open a new Rmd file as follows:
File -> New File -> R Markdown
The first segment of the document indicate its information (e.g., the title, author, and date) and characteristics (e.g., the output format).
You can render the file clicking the Knit button in the top of the script area. Please save your file as Test.Rmd.The result is:
Please note that you have text and code embedded in the same document. To add text, you have simply to write it. To add code, you have to embed it inside a code chunk, which starts and ends with three backticks ```.
r indicates the name of the programming language.This code chunk can have several options that must be added between the programming language (r) and the closing curly bracket (}).
You can insert a new code chunk with the keyboard shorcut Ctrl + Alt + I (OS X: Cmd + Option + I).
eval = FALSE prevents code to run. It will serve just for rendering purposes.
include = FALSE prevents code and results from appearing in the finished file. R Markdown still runs the code in the chunk, and the results can be used by other chunks.
echo = FALSE prevents code, but not the results from appearing in the finished file. This is a useful way to embed figures.
message = FALSE prevents messages that are generated by code from appearing in the finished file.
warning = FALSE prevents warnings that are generated by code from appearing in the finished.
fig.align aligns the figure to the ‘center’, ‘right’ or ‘left’.
fig.cap = “…” adds a caption to graphical results.
There are several formats available in rmarkdown:
The text in an R Markdown document is written in Pandoc’s Markdown.
italics: surrounded by underscores (_) or asterisks(*); e.g., italics.
bold: surrounded by double underscores (__) or asterisks(**); e.g., bold.
subscript: surrounded by tildes (~); e.g., wordsubscript.
superscript: surrounded by tildes (^); e.g., wordsuperscript.
inline code: surrounded by backticks (`); e.g., code.
To add bibliography please visit Section 2.8 of Authoring Books with R Markdown.
Let’s create a simple PDF document as an example and name it Random numbers.
---
title: "Random numbers"
author: "Oscar M. Baez-Villanueva"
date: "`r Sys.Date()`"
output: pdf_document
---Later on, we can add a code chunk to specify that all code should be visible.
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
We can add some text:
norm to generate a matrix of 60 normally distributed random values with six columns:
```{r}
x <- matrix(rnorm(60), ncol = 6)
print(x)
```
Then, some more text:
```{r}
vals <- as.numeric(x)
m <- mean(vals)
```
Additionally, we can show values stored in variables in the text as follows:
The mean value of these numbers is: `r m`. Additionally, `r max(vals)` is the maximum value, and `r min(vals)` the minimum.
Finally, we can use the function boxplot to visualise the data:
```{r fig.align='center', fig.cap="Boxplot of random numbers"}
boxplot(x)
```
Leaflet is a widely used open-source JavaScript library for interactive maps. The leaflet package helps you to integrate and control Leaflet maps in R. This package will help you to render spatial data and share the results in a very interesting way.
Please install the leaflet package.
Now, lease load it:
Let’s create a basic map widget:
m <- leaflet()
m <- setView(m, lng = -99.179, lat = 21.801, zoom = 5)
m <- addTiles(m)
m <- addMarkers(m, lng = -99.179, lat = 21.801, popup = "A place to visit!")
mAdditionally, we can use the magrittr pipe:
There are several nice map themes here.
We can add polygons to the plots. Let’s read the shapefile of a catchment in Chile and its river network with the sf package.
catch <- "C:/Data/Shapefile/Trancura_catchment.shp"
rivers <- "C:/Data/Shapefile/Trancura_rivers.shp"
catch <- read_sf(catch)
rivers <- read_sf(rivers)Let’s plot the data:
leaflet(width="100%") %>%
addTiles() %>%
addPolygons(data=catch, weight = 3, color = "blue", popup = ~ NOMBRE, group = "Catchment") %>%
addPolygons(data=rivers, weight = 3, color = "cyan", group = "Rivers") %>%
addLayersControl(
overlayGroups = c("Catchment", "Rivers"),
options = layersControlOptions(collapsed = FALSE)
)Let’s use the raster package to import the raster layers as the terra package is still not supported by leaflet.
rfmep <- "../Data/L5_RMarkdown/Raster/RF-MEP_1990-2018_multiannual.tif"
mswep <- "../Data/L5_RMarkdown/Raster/MSWEPv2.8_1990-2018_multiannual.tif"
rfmep <- raster(rfmep)
mswep <- raster(mswep)
r <- stack(rfmep, mswep)
pal <- colorNumeric(c("#0C2C84", "#41B6C4", "#FFFFCC"), values(r),
na.color = "transparent")To add raster files:
leaflet(width="100%") %>%
addTiles() %>%
addRasterImage(r[[1]], colors = pal, opacity = 0.8, group = "RF-MEP") %>%
addRasterImage(r[[2]], colors = pal, opacity = 0.8, group = "MSWEPv2.8") %>%
addPolygons(data=catch, weight = 3, color = "blue", popup = ~ NOMBRE, group = "Catchment") %>%
addPolygons(data=rivers, weight = 3, color = "cyan", group = "Rivers") %>%
addLegend(pal = pal, values = values(r), title = "P [mm]") %>%
addLayersControl(
baseGroups = c("RF-MEP", "MSWEPv2.8"),
overlayGroups = c("Catchment", "Rivers"),
options = layersControlOptions(collapsed = FALSE),
)